<?php
namespace app\common\library\mstching;
use app\common\model\WebSet;
use app\common\model\PrinterLog;

/*
 * 对对机驱动模块
 * 测试机型：D1,D2,M1
*/
class PrintHelper
{
	private $baseurl = '';
	private $appid = '';		
	private $appsecret = '';
	
	/**
	 * 构造函数
	 */
	public function __construct()
	{
		$values = WebSet::getItem('printer');
		$this->baseurl = $values['ddj']['api_url'];
		$this->appid = $values['ddj']['app_key'];
		$this->appsecret = $values['ddj']['app_secret'];
	}

    /*
     * 用户设备绑定
     * $uuid 设备编号
     * $userId 与对对机平台关联的用户唯一标示（你自己系统定义的）
	 * $deviceName 自定义设备名称
	 * 返回数据格式：{"OpenUserId":1251,"Code":200,"Message":"成功"}
     */
	public function userBind($uuid, $userId, $deviceName)
    {
        $url = $this->getUrl("/home/userbind");
        $data = [
            'Uuid' => $uuid,
            'UserId' => $userId,
            'DeviceName' => $deviceName
        ];
		$userBind = json_decode(http_post($url, $data,$this->http_head($data)),true);
		$userBind['Message'] = $this->p_err($userBind['Code']);
        return $userBind;
    }
	
    /*
     * 获取设备状态                          
     * $uuid 设备编号
	 * 返回数据格式：{"State":0,"Code":200,"Message":"成功"}
	 * State状态值(-1错误 0正常 1缺纸 2温度保护报警 3忙碌 4离线)
     */
    public function getDeviceState($uuid)
	{
        $url = $this->getUrl("/home/getdevicestate");
        $data = ['Uuid' => $uuid];
		$DeviceState = json_decode(http_post($url, $data,$this->http_head($data)),true);
		if($DeviceState['Code']==200){//查询成功
			return $this->p_state($DeviceState['State']);
		}
        return $this->p_err($DeviceState['Code']);
    }
	
    /*
     * 打印信息
     * $uuid 设备编号
     * $content 打印的内容
     * $OpenUserId 调用 userBind函数返回的openUserId
     * $order 打印订单数据
     * $p_n 打印份数
     * $model 设备型号
     * $tpl 模板类型
	 * 返回数据格式：{"TaskId":1,"Code":200,"Message":"成功"}
	 * TaskId  打印任务编号
     */
    public function printContent($uuid,$openUserId,$order,$p_n,$model,$tpl)
	{
		if($tpl==0){
			$content = $this->make_order_templet($order,$model);//生成订单模板
		}else{
			$content = $this->make_refund_templet($order,$model);//生成退单模板
		}
        $url = $this->getUrl("/home/printcontent2");
        $data = [
        	'Uuid' => $uuid,
        	'PrintContent'=>' '.$content,
        	'OpenUserId'=>$openUserId
        ];
        for($n=0;$n<$p_n;$n++){
			$pll = json_decode(http_post($url, $data,$this->http_head($data)),true);
			if($pll['Code']!=200){//绑定不成功
				//记录打印失败日志
				$model = new PrinterLog;
				$model->save([
					'brand' => 10,
					'open_user_id' => $openUserId,
					'uuid' => $uuid,
					'tpl' => $tpl,
					'content' => $content,
					'order_no' => $order['order_no'],
					'shop_id' => $order['shop_id'],
					'wxapp_id' => $order['wxapp_id']
				]);
			}
		}
		return true;
    }
	
    /*
     * 打印网页信息
     * $uuid 设备编号
     * $printUrl 打印网页地址
     * $OpenUserId 调用 userBind函数返回的openUserId
     */
    public function  printHtmlContent($uuid,$printUrl,$openUserId)
	{
        $url = $this->getUrl("/home/printhtmlcontent");
        $jsonStr = json_encode(array('Uuid' => $uuid,'PrintUrl'=>$printUrl,'OpenUserId'=>$openUserId));
        return $this->http_post_json($url, $jsonStr);
    }
	
    /*
     * 查询任务状态
     * $taskId 任务编号
     */
    public function getPrintTaskState($taskId)
	{
        $url = $this->getUrl("/home/getprinttaskstate");
        $jsonStr = json_encode(array('TaskId' => $taskId));
        return $this->http_post_json($url, $jsonStr);
    }
	
	
	//创建通用请求参数
	private function createParams()
	{
		$nonce = $this->getNonce();
		$timeStamp = $this->getTimestamp();
		$signStr = $this->signatureString($this->appsecret, $timeStamp, $nonce);
		return '?appid='.$this->appid.'&nonce='.$nonce.'&'.'timestamp='.$timeStamp.'&signature='.$signStr;
	}
	//获取请求url
	private function getUrl($action)
	{
		$params = $this->createParams();
		return $this->baseurl.$action.$params;
	}
	//获取随机数
	private function getNonce()
	{
		return ''.rand(100000000,999999999);
	}
	//获取时间戳
	private function getTimestamp()
	{    
		return ''.intval(time());
	}
	//sha1 加密
	private function signatureString($appSecret,$timestamp,$nonce)
	{    
		$arrTmp = array($appSecret,$timestamp,$nonce);
		asort($arrTmp,SORT_LOCALE_STRING);
		$strTmp = implode('', $arrTmp);
		return strtolower(sha1($strTmp));
	}
	
	/**
	 * 生成请求头文件
	 */
	private function http_head($data)
	{
		return [
			'Content-Type: application/json; charset=utf-8',
			'Content-Length: ' . strlen(json_encode($data))
		];
	}
	
	//设备状态
	private function p_state($value)
	{
		if($value<0 OR $value>4){
			return '错误';
		}
		$state = [
			'0' => '正常',
			'1' => '缺纸',
			'2' => '高温',
			'3' => '忙碌',
			'4' => '离线'
		];
		return $state[$value];
		
	}
	
	//服务请求错误代码
	private function p_err($code='')
	{
		if(empty($code)){
			return '未知';
		}
		$err = [
			'200' => '成功',
			'1000' => '服务处理异常',
			'1001' => '验证签名错误',
			'1002' => '链接失效',
			'1003' => '参数错误',
			'1004' => 'AppId不存在',
			'1005' => '设备不存在',
			'1006' => '开发者账号已被禁用',
			'1007' => '任务不存在或权限不足',
			'1008' => '未通过认证',
			'1009' => '限制调用',
			'1010' => '设备未连接',
			'1011' => '与服务器断开链接',
			'1012' => '打印任务不能为空'
		];
		return $err[$code];
	}		

	/**
	 * 制作订单模板
	 * $data 订单数据
	 * $model 打印机型号 
	 */
	private function make_order_templet($data,$model=2)
	{
		$content = [];
		$code = 'UTF-8//IGNORE'; //默认D2
		$font_b = 3;
		$font_s = 0;
		$font_m = 11;
		$str = "................................................";
		if($model==1){ //如果是D1机型
			$code = 'GBK//IGNORE';
			$font_b = 1;
			$font_s = 0;
			$font_m = 0;
			$str = "................................";
		}
		if($data['order_mode']['value']==10){
			if(isset($data['table']['table_name'])){
				$title = $data['table']['table_name'];
			}else{
				$title = '堂食'.$data['row_no'].'号';
			}
		}
		if($data['order_mode']['value']==20){
			$title = '外卖'.$data['row_no'].'号';
		}
		if($data['order_mode']['value']==30){
			$title = '自取'.$data['row_no'].'号';
		}
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 1,
			'Bold' => 1,
			'FontSize' => $font_b,
			'BaseText' => base64_encode(iconv('UTF-8', $code, '# ' . $title . ' #'))
		];
		if($data['arrive_time']['value']>0){
			$content[] = [
				'PrintType' => 0,
				'Alignment' => 0,
				'Bold' => 0,
				'FontSize' => $font_s,
				'BaseText' => base64_encode(iconv('UTF-8', $code, '到店时间：' . $data['arrive_time']['text']))
			];
		}
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 0,
			'Bold' => 0,
			'FontSize' => $font_m,
			'BaseText' => base64_encode(iconv('UTF-8', $code, $str))
		];
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 1,
			'Bold' => 0,
			'FontSize' => $font_s,
			'BaseText' => base64_encode(iconv('UTF-8', $code, $data['shop']['shop_name']))
		];
		if($data['transaction_id']){
			$pay_title = '微信支付';
		}else{
			$pay_title = '余额支付';
		}
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 1,
			'Bold' => 0,
			'FontSize' => $font_s,
			'BaseText' => base64_encode(iconv('UTF-8', $code, '-- ' . $pay_title . ' --'))
		];
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 0,
			'Bold' => 0,
			'FontSize' => $font_s,
			'BaseText' => base64_encode(iconv('UTF-8', $code, '支付时间：'.date("Y-m-d H:i:s",$data['pay_time'])))
		];
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 0,
			'Bold' => 0,
			'FontSize' => $font_b,
			'BaseText' => base64_encode(iconv('UTF-8', $code, '名称        数量'))
		];
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 0,
			'Bold' => 0,
			'FontSize' => $font_m,
			'BaseText' => base64_encode(iconv('UTF-8', $code, $str))
		];

		//循环拼接打印模板
		for ($i = 0; $i < sizeof($data['goods']); $i++) {
			$goods_name = $data['goods'][$i]['goods_name'].$data['goods'][$i]['goods_attr'];//产品名字
			//设置名称字符长度
			$lan = mb_strlen($goods_name,'utf-8')*2;//
			for($n=$lan;$n<13;$n++){
				$goods_name .= ' ';
			}
			$total_num = $data['goods'][$i]['total_num'];	//产品数量
			$content[] = [
				'PrintType' => 0,
				'Alignment' => 0,
				'Bold' => 0,
				'FontSize' => $font_b,
				'BaseText' => base64_encode(iconv('UTF-8', $code, $goods_name . "×" . $total_num))
			];
		}
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 0,
			'Bold' => 0,
			'FontSize' => $font_m,
			'BaseText' => base64_encode(iconv('UTF-8', $code, $str))
		];
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 0,
			'Bold' => 0,
			'FontSize' => $font_s,
			'BaseText' => base64_encode(iconv('UTF-8', $code, '商品金额：+￥'.$data['total_price']))
		];

		if($data['express_price']>0){
			$content[] = [
				'PrintType' => 0,
				'Alignment' => 0,
				'Bold' => 0,
				'FontSize' => $font_s,
				'BaseText' => base64_encode(iconv('UTF-8', $code, '配送费用：+￥'.$data['express_price']))
			];
		}
		if($data['pack_price']>0){
			$content[] = [
				'PrintType' => 0,
				'Alignment' => 0,
				'Bold' => 0,
				'FontSize' => $font_s,
				'BaseText' => base64_encode(iconv('UTF-8', $code, '餐盒费用：+￥'.$data['pack_price']))
			];
		}
		if($data['ware_price']>0){
			$content[] = [
				'PrintType' => 0,
				'Alignment' => 0,
				'Bold' => 0,
				'FontSize' => $font_s,
				'BaseText' => base64_encode(iconv('UTF-8', $code, '餐具调料：+￥'.$data['ware_price']))
			];
		}
		if($data['activity_price']>0){
			$content[] = [
				'PrintType' => 0,
				'Alignment' => 0,
				'Bold' => 0,
				'FontSize' => $font_s,
				'BaseText' => base64_encode(iconv('UTF-8', $code, '优惠金额：-￥'.$data['activity_price']))
			];
		}
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 0,
			'Bold' => 0,
			'FontSize' => $font_s,
			'BaseText' => base64_encode(iconv('UTF-8', $code, '实付金额：￥'.$data['pay_price']))
		];
		if($data['flavor']){
			$content[] = [
				'PrintType' => 0,
				'Alignment' => 0,
				'Bold' => 0,
				'FontSize' => $font_s,
				'BaseText' => base64_encode(iconv('UTF-8', $code, '口味要求：'.$data['flavor']))
			];
		}
		if($data['message']){
			$content[] = [
				'PrintType' => 0,
				'Alignment' => 0,
				'Bold' => 0,
				'FontSize' => $font_s,
				'BaseText' => base64_encode(iconv('UTF-8', $code, '顾客留言：'.$data['message']))
			];
		}
		
		if($data['order_mode']['value']==20){
			$content[] = [
				'PrintType' => 0,
				'Alignment' => 0,
				'Bold' => 0,
				'FontSize' => $font_s,
				'BaseText' => base64_encode(iconv('UTF-8', $code, '配送地址：'.$data['address']['detail']))
			];
			$content[] = [
				'PrintType' => 0,
				'Alignment' => 0,
				'Bold' => 0,
				'FontSize' => $font_s,
				'BaseText' => base64_encode(iconv('UTF-8', $code, '接 收 人：'.$data['address']['name'].$data['address']['phone']))
			];
		}
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 1,
			'Bold' => 1,
			'FontSize' => $font_b,
			'BaseText' => base64_encode(iconv('UTF-8', $code, '# ' . $title . ' # 完'))
		];
		return json_encode($content);
	}
	
	/**
	 * 制作退单模板
	 * $data 退单数据
	 * $model 打印机型号 
	 */
	private function make_refund_templet($data,$model=2)
	{
		$content = [];
		$code = 'UTF-8//IGNORE'; //默认D2
		$font_b = 3;
		$font_s = 13;
		$font_m = 11;
		$str = "................................................";
		if($model==1){ //如果是D1机型
			$code = 'GBK//IGNORE';
			$font_b = 1;
			$font_s = 0;
			$font_m = 0;
			$str = "................................";
		}
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 1,
			'Bold' => 1,
			'FontSize' => $font_b,
			'BaseText' => base64_encode(iconv('UTF-8', $code, '# 退单 #'))
		]; 
		 
		if($data['order_mode']['value']==10){
			if(isset($data['table']['table_name'])){
				$title = $data['table']['table_name'];
			}else{
				$title = '堂食'.$data['row_no'].'号';
			}
		}
		if($data['order_mode']['value']==20){
			$title = '外卖'.$data['row_no'].'号';
		}
		if($data['order_mode']['value']==30){
			$title = '自取'.$data['row_no'].'号';
		}

		$content[] = [
			'PrintType' => 0,
			'Alignment' => 1,
			'Bold' => 1,
			'FontSize' => $font_b,
			'BaseText' => base64_encode(iconv('UTF-8', $code, '- ' . $title))
		];
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 0,
			'Bold' => 0,
			'FontSize' => $font_m,
			'BaseText' => base64_encode(iconv('UTF-8', $code, $str))
		];
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 1,
			'Bold' => 0,
			'FontSize' => $font_s,
			'BaseText' => base64_encode(iconv('UTF-8', $code, $data['shop']['shop_name']))
		];
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 0,
			'Bold' => 0,
			'FontSize' => $font_b,
			'BaseText' => base64_encode(iconv('UTF-8', $code, '名称        数量'))
		];
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 0,
			'Bold' => 0,
			'FontSize' => $font_m,
			'BaseText' => base64_encode(iconv('UTF-8', $code, $str))
		];
		//循环拼接打印模板
		for ($i = 0; $i < sizeof($data['goods']); $i++) {
			if($data['goods'][$i]['refund_num']>0){
				$goods_name = $data['goods'][$i]['goods_name'].$data['goods'][$i]['goods_attr'];//产品名字
				//设置名称字符长度
				$lan = mb_strlen($goods_name,'utf-8')*2;//
				for($n=$lan;$n<13;$n++){
					$goods_name .= ' ';
				}
				$refund_num=$data['goods'][$i]['refund_num'];	//产品数量
				$content[] = [
					'PrintType' => 0,
					'Alignment' => 0,
					'Bold' => 0,
					'FontSize' => $font_b,
					'BaseText' => base64_encode(iconv('UTF-8', $code, $goods_name . "×" . $refund_num))
				];
			}
		}
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 0,
			'Bold' => 0,
			'FontSize' => $font_m,
			'BaseText' => base64_encode(iconv('UTF-8', $code, $str))
		];
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 0,
			'Bold' => 0,
			'FontSize' => $font_s,
			'BaseText' => base64_encode(iconv('UTF-8', $code, '付款金额：￥'.$data['pay_price']))
		];
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 0,
			'Bold' => 0,
			'FontSize' => $font_s,
			'BaseText' => base64_encode(iconv('UTF-8', $code, '退款金额：￥'.$data['refund_price']))
		];
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 0,
			'Bold' => 0,
			'FontSize' => $font_s,
			'BaseText' => base64_encode(iconv('UTF-8', $code, '退款理由：'.$data['refund_desc']))
		];
		$content[] = [
			'PrintType' => 0,
			'Alignment' => 1,
			'Bold' => 1,
			'FontSize' => $font_b,
			'BaseText' => base64_encode(iconv('UTF-8', $code, '# 退单 # 完'))
		];
		return json_encode($content);
	}
}